﻿using System;
using System.Drawing;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using Microsoft.VisualBasic;
using System.Collections;
using System.Net;
using System.Collections.Generic;
namespace LCL {
    /// <summary>
    /// 工具类
    /// </summary>
    public partial class Utils {
        /// <summary>
        /// 获取系统框架的版本号
        /// </summary>
        /// <remarks>
        /// 当你要显示本组件框架的版本号的时候，就可以用这个属性来显示
        /// </remarks>
        public static SystemVersion FrameworkVersion { get { return new SystemVersion("1.0.0"); } }
        /// <summary>
        /// 得到正则编译参数设置
        /// </summary>
        /// <returns>参数设置</returns>
        public static RegexOptions GetRegexCompiledOptions() {
            return RegexOptions.None;
        }
        public static bool IsCompriseStr(string str, string stringarray, string strsplit) {
            if(stringarray.StrIsNullOrEmpty())
                return false;
            str=str.ToLower();
            string[] stringArray = Utils.SplitString(stringarray.ToLower(), strsplit);
            for(int i = 0; i<stringArray.Length; i++) {
                if(str.IndexOf(stringArray[i])>-1) {
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 判断指定字符串在指定字符串数组中的位置
        /// </summary>
        /// <param name="strSearch">字符串</param>
        /// <param name="stringArray">字符串数组</param>
        /// <param name="caseInsensetive">是否不区分大小写, true为不区分, false为区分</param>
        /// <returns>字符串在指定字符串数组中的位置, 如不存在则返回-1</returns>
        public static int GetInArrayID(string strSearch, string[] stringArray, bool caseInsensetive) {
            for(int i = 0; i<stringArray.Length; i++) {
                if(caseInsensetive) {
                    if(strSearch.ToLower()==stringArray[i].ToLower())
                        return i;
                } else if(strSearch==stringArray[i])
                    return i;
            }
            return -1;
        }
        /// <summary>
        /// 判断指定字符串在指定字符串数组中的位置
        /// </summary>
        /// <param name="strSearch">字符串</param>
        /// <param name="stringArray">字符串数组</param>
        /// <returns>字符串在指定字符串数组中的位置, 如不存在则返回-1</returns>		
        public static int GetInArrayID(string strSearch, string[] stringArray) {
            return GetInArrayID(strSearch, stringArray, true);
        }
        /// <summary>
        /// 判断指定字符串是否属于指定字符串数组中的一个元素
        /// </summary>
        /// <param name="strSearch">字符串</param>
        /// <param name="stringArray">字符串数组</param>
        /// <param name="caseInsensetive">是否不区分大小写, true为不区分, false为区分</param>
        /// <returns>判断结果</returns>
        public static bool InArray(string strSearch, string[] stringArray, bool caseInsensetive) {
            return GetInArrayID(strSearch, stringArray, caseInsensetive)>=0;
        }
        /// <summary>
        /// 判断指定字符串是否属于指定字符串数组中的一个元素
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="stringarray">字符串数组</param>
        /// <returns>判断结果</returns>
        public static bool InArray(string str, string[] stringarray) {
            return InArray(str, stringarray, false);
        }
        /// <summary>
        /// 判断指定字符串是否属于指定字符串数组中的一个元素
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="stringarray">内部以逗号分割单词的字符串</param>
        /// <returns>判断结果</returns>
        public static bool InArray(string str, string stringarray) {
            return InArray(str, SplitString(stringarray, ","), false);
        }
        /// <summary>
        /// 判断指定字符串是否属于指定字符串数组中的一个元素
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="stringarray">内部以逗号分割单词的字符串</param>
        /// <param name="strsplit">分割字符串</param>
        /// <returns>判断结果</returns>
        public static bool InArray(string str, string stringarray, string strsplit) {
            return InArray(str, SplitString(stringarray, strsplit), false);
        }
        /// <summary>
        /// 判断指定字符串是否属于指定字符串数组中的一个元素
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="stringarray">内部以逗号分割单词的字符串</param>
        /// <param name="strsplit">分割字符串</param>
        /// <param name="caseInsensetive">是否不区分大小写, true为不区分, false为区分</param>
        /// <returns>判断结果</returns>
        public static bool InArray(string str, string stringarray, string strsplit, bool caseInsensetive) {
            return InArray(str, SplitString(stringarray, strsplit), caseInsensetive);
        }
        /// <summary>
        /// 获得当前绝对路径
        /// </summary>
        /// <param name="strPath">指定的路径</param>
        /// <returns>绝对路径</returns>
        public static string GetMapPath(string strPath) {
            if(HttpContext.Current!=null) {
                return HttpContext.Current.Server.MapPath(strPath);
            } else //非web程序引用
              {
                strPath=strPath.Replace("/", "\\").Replace("~/", "").Replace("~\\", "");
                if(strPath.StartsWith("\\")) {
                    strPath=strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\');
                }
                return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
            }
        }
        /// <summary>
        /// int型转换为string型
        /// </summary>
        /// <returns>转换后的string类型结果</returns>
        public static string IntToStr(int intValue) {
            return Convert.ToString(intValue);
        }
        public static string GetUnicodeSubString(string str, int len, string p_TailString) {
            str=str.TrimEnd();
            string result = string.Empty;// 最终返回的结果
            int byteLen = System.Text.Encoding.Default.GetByteCount(str);// 单字节字符长度
            int charLen = str.Length;// 把字符平等对待时的字符串长度
            int byteCount = 0;// 记录读取进度
            int pos = 0;// 记录截取位置
            if(byteLen>len) {
                for(int i = 0; i<charLen; i++) {
                    if(Convert.ToInt32(str.ToCharArray()[i])>255)// 按中文字符计算加2
                        byteCount+=2;
                    else// 按英文字符计算加1
                        byteCount+=1;
                    if(byteCount>len)// 超出时只记下上一个有效位置
                    {
                        pos=i;
                        break;
                    } else if(byteCount==len)// 记下当前位置
                      {
                        pos=i+1;
                        break;
                    }
                }
                if(pos>=0)
                    result=str.Substring(0, pos)+p_TailString;
            } else
                result=str;
            return result;
        }
        /// <summary>
        /// 自定义的替换字符串函数
        /// </summary>
        public static string ReplaceString(string SourceString, string SearchString, string ReplaceString, bool IsCaseInsensetive) {
            return Regex.Replace(SourceString, Regex.Escape(SearchString), ReplaceString, IsCaseInsensetive ? RegexOptions.IgnoreCase : RegexOptions.None);
        }
        /// <summary>
        /// 生成指定数量的html空格符号
        /// </summary>
        public static string GetSpacesString(int spacesCount) {
            StringBuilder sb = new StringBuilder();
            for(int i = 0; i<spacesCount; i++) {
                sb.Append(" &nbsp;&nbsp;");
            }
            return sb.ToString();
        }
        /// <summary>
        /// 返回URL中结尾的文件名
        /// </summary>		
        public static string GetFilename(string url) {
            if(url==null) {
                return "";
            }
            string[] strs1 = url.Split(new char[] { '/' });
            return strs1[strs1.Length-1].Split(new char[] { '?' })[0];
        }
        /// <summary>
        /// 返回标准日期格式string
        /// </summary>
        public static string GetDate() {
            return DateTime.Now.ToString("yyyy-MM-dd");
        }
        /// <summary>
        /// 返回指定日期格式
        /// </summary>
        public static string GetDate(string datetimestr, string replacestr) {
            if(datetimestr==null)
                return replacestr;
            if(datetimestr.Equals(""))
                return replacestr;
            try {
                datetimestr=Convert.ToDateTime(datetimestr).ToString("yyyy-MM-dd").Replace("1900-01-01", replacestr);
            } catch {
                return replacestr;
            }
            return datetimestr;
        }
        /// <summary>
        /// 返回标准时间 
        /// </sumary>
        public static string GetStandardDateTime(string fDateTime, string formatStr) {
            if(fDateTime=="0000-0-0 0:00:00")
                return fDateTime;
            DateTime time = new DateTime(1900, 1, 1, 0, 0, 0, 0);
            if(DateTime.TryParse(fDateTime, out time))
                return time.ToString(formatStr);
            else
                return "N/A";
        }
        /// <summary>
        /// 返回标准时间 yyyy-MM-dd HH:mm:ss
        /// </sumary>
        public static string GetStandardDateTime(string fDateTime) {
            return GetStandardDateTime(fDateTime, "yyyy-MM-dd HH:mm:ss");
        }
        /// <summary>
        /// 返回标准时间 yyyy-MM-dd
        /// </sumary>
        public static string GetStandardDate(string fDate) {
            return GetStandardDateTime(fDate, "yyyy-MM-dd");
        }
        public static string GetIP() {
            return LRequest.GetIP();
        }
        /// <summary>
        /// 转换为静态html
        /// </summary>
        public void transHtml(string path, string outpath) {
            Page page = new Page();
            StringWriter writer = new StringWriter();
            page.Server.Execute(path, writer);
            FileStream fs;
            if(File.Exists(page.Server.MapPath("")+"\\"+outpath)) {
                File.Delete(page.Server.MapPath("")+"\\"+outpath);
                fs=File.Create(page.Server.MapPath("")+"\\"+outpath);
            } else {
                fs=File.Create(page.Server.MapPath("")+"\\"+outpath);
            }
            byte[] bt = Encoding.Default.GetBytes(writer.ToString());
            fs.Write(bt, 0, bt.Length);
            fs.Close();
        }
        /// <summary>
        /// 分割字符串
        /// </summary>
        public static string[] SplitString(string strContent, string strSplit) {
            if(!strContent.StrIsNullOrEmpty()) {
                if(strContent.IndexOf(strSplit)<0)
                    return new string[] { strContent };
                return Regex.Split(strContent, Regex.Escape(strSplit), RegexOptions.IgnoreCase);
            } else
                return new string[0] { };
        }
        /// <summary>
        /// 分割字符串
        /// </summary>
        /// <returns></returns>
        public static string[] SplitString(string strContent, string strSplit, int count) {
            string[] result = new string[count];
            string[] splited = SplitString(strContent, strSplit);
            for(int i = 0; i<count; i++) {
                if(i<splited.Length)
                    result[i]=splited[i];
                else
                    result[i]=string.Empty;
            }
            return result;
        }
        /// <summary>
        /// 过滤字符串数组中每个元素为合适的大小
        /// 当长度小于minLength时，忽略掉,-1为不限制最小长度
        /// 当长度大于maxLength时，取其前maxLength位
        /// 如果数组中有null元素，会被忽略掉
        /// </summary>
        /// <param name="minLength">单个元素最小长度</param>
        /// <param name="maxLength">单个元素最大长度</param>
        /// <returns></returns>
        public static string[] PadStringArray(string[] strArray, int minLength, int maxLength) {
            if(minLength>maxLength) {
                int t = maxLength;
                maxLength=minLength;
                minLength=t;
            }
            int iMiniStringCount = 0;
            for(int i = 0; i<strArray.Length; i++) {
                if(minLength>-1&&strArray[i].Length<minLength) {
                    strArray[i]=null;
                    continue;
                }
                if(strArray[i].Length>maxLength)
                    strArray[i]=strArray[i].Substring(0, maxLength);
                iMiniStringCount++;
            }
            string[] result = new string[iMiniStringCount];
            for(int i = 0, j = 0; i<strArray.Length&&j<result.Length; i++) {
                if(strArray[i]!=null&&strArray[i]!=string.Empty) {
                    result[j]=strArray[i];
                    j++;
                }
            }
            return result;
        }
        /// <summary>
        /// 分割字符串
        /// </summary>
        /// <param name="strContent">被分割的字符串</param>
        /// <param name="strSplit">分割符</param>
        /// <param name="ignoreRepeatItem">忽略重复项</param>
        /// <param name="maxElementLength">单个元素最大长度</param>
        /// <returns></returns>
        public static string[] SplitString(string strContent, string strSplit, bool ignoreRepeatItem, int maxElementLength) {
            string[] result = SplitString(strContent, strSplit);
            return ignoreRepeatItem ? DistinctStringArray(result, maxElementLength) : result;
        }
        public static string[] SplitString(string strContent, string strSplit, bool ignoreRepeatItem, int minElementLength, int maxElementLength) {
            string[] result = SplitString(strContent, strSplit);
            if(ignoreRepeatItem) {
                result=DistinctStringArray(result);
            }
            return PadStringArray(result, minElementLength, maxElementLength);
        }
        /// <summary>
        /// 分割字符串
        /// </summary>
        /// <param name="strContent">被分割的字符串</param>
        /// <param name="strSplit">分割符</param>
        /// <param name="ignoreRepeatItem">忽略重复项</param>
        /// <returns></returns>
        public static string[] SplitString(string strContent, string strSplit, bool ignoreRepeatItem) {
            return SplitString(strContent, strSplit, ignoreRepeatItem, 0);
        }
        /// <summary>
        /// 清除字符串数组中的重复项
        /// </summary>
        /// <param name="strArray">字符串数组</param>
        /// <param name="maxElementLength">字符串数组中单个元素的最大长度</param>
        /// <returns></returns>
        public static string[] DistinctStringArray(string[] strArray, int maxElementLength) {
            Hashtable h = new Hashtable();
            foreach(string s in strArray) {
                string k = s;
                if(maxElementLength>0&&k.Length>maxElementLength) {
                    k=k.Substring(0, maxElementLength);
                }
                h[k.Trim()]=s;
            }
            string[] result = new string[h.Count];
            h.Keys.CopyTo(result, 0);
            return result;
        }
        /// <summary>
        /// 清除字符串数组中的重复项
        /// </summary>
        /// <param name="strArray">字符串数组</param>
        /// <returns></returns>
        public static string[] DistinctStringArray(string[] strArray) {
            return DistinctStringArray(strArray, 0);
        }
        /// <summary>
        /// 进行指定的替换(脏字过滤)
        /// </summary>
        public static string StrFilter(string str, string bantext) {
            string text1 = "", text2 = "";
            string[] textArray1 = SplitString(bantext, "\r\n");
            for(int num1 = 0; num1<textArray1.Length; num1++) {
                text1=textArray1[num1].Substring(0, textArray1[num1].IndexOf("="));
                text2=textArray1[num1].Substring(textArray1[num1].IndexOf("=")+1);
                str=str.Replace(text1, text2);
            }
            return str;
        }
        /// <summary>
        /// 返回指定目录下的非 UTF8 字符集文件
        /// </summary>
        /// <param name="Path">路径</param>
        /// <returns>文件名的字符串数组</returns>
        public static string[] FindNoUTF8File(string Path) {
            StringBuilder filelist = new StringBuilder();
            DirectoryInfo Folder = new DirectoryInfo(Path);
            FileInfo[] subFiles = Folder.GetFiles();
            for(int j = 0; j<subFiles.Length; j++) {
                if(subFiles[j].Extension.ToLower().Equals(".htm")) {
                    FileStream fs = new FileStream(subFiles[j].FullName, FileMode.Open, FileAccess.Read);
                    bool bUtf8 = IsUTF8(fs);
                    fs.Close();
                    if(!bUtf8) {
                        filelist.Append(subFiles[j].FullName);
                        filelist.Append("\r\n");
                    }
                }
            }
            return Utils.SplitString(filelist.ToString(), "\r\n");
        }
        //0000 0000-0000 007F - 0xxxxxxx  (ascii converts to 1 octet!)
        //0000 0080-0000 07FF - 110xxxxx 10xxxxxx    ( 2 octet format)
        //0000 0800-0000 FFFF - 1110xxxx 10xxxxxx 10xxxxxx (3 octet format)
        /// <summary>
        /// 判断文件流是否为UTF8字符集
        /// </summary>
        /// <param name="sbInputStream">文件流</param>
        /// <returns>判断结果</returns>
        private static bool IsUTF8(FileStream sbInputStream) {
            int i;
            byte cOctets;  // octets to go in this UTF-8 encoded character 
            byte chr;
            bool bAllAscii = true;
            long iLen = sbInputStream.Length;
            cOctets=0;
            for(i=0; i<iLen; i++) {
                chr=(byte)sbInputStream.ReadByte();
                if((chr&0x80)!=0)
                    bAllAscii=false;
                if(cOctets==0) {
                    if(chr>=0x80) {
                        do {
                            chr<<=1;
                            cOctets++;
                        }
                        while((chr&0x80)!=0);
                        cOctets--;
                        if(cOctets==0)
                            return false;
                    }
                } else {
                    if((chr&0xC0)!=0x80)
                        return false;
                    cOctets--;
                }
            }
            if(cOctets>0)
                return false;
            if(bAllAscii)
                return false;
            return true;
        }
        /// <summary>
        /// 格式化字节数字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string FormatBytesStr(int bytes) {
            if(bytes>1073741824)
                return ((double)(bytes/1073741824)).ToString("0")+"G";
            if(bytes>1048576)
                return ((double)(bytes/1048576)).ToString("0")+"M";
            if(bytes>1024)
                return ((double)(bytes/1024)).ToString("0")+"K";
            return bytes.ToString()+"Bytes";
        }
        /// <summary>
        /// 返回指定IP是否在指定的IP数组所限定的范围内, IP数组内的IP地址可以使用*表示该IP段任意, 例如192.168.1.*
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="iparray"></param>
        /// <returns></returns>
        public static bool InIPArray(string ip, string[] iparray) {
            string[] userip = Utils.SplitString(ip, @".");
            for(int ipIndex = 0; ipIndex<iparray.Length; ipIndex++) {
                string[] tmpip = Utils.SplitString(iparray[ipIndex], @".");
                int r = 0;
                for(int i = 0; i<tmpip.Length; i++) {
                    if(tmpip[i]=="*")
                        return true;
                    if(userip.Length>i) {
                        if(tmpip[i]==userip[i])
                            r++;
                        else
                            break;
                    } else
                        break;
                }
                if(r==4)
                    return true;
            }
            return false;
        }
        /// <summary>
        /// 备份文件
        /// </summary>
        /// <param name="sourceFileName">源文件名</param>
        /// <param name="destFileName">目标文件名</param>
        /// <param name="overwrite">当目标文件存在时是否覆盖</param>
        /// <returns>操作是否成功</returns>
        public static bool BackupFile(string sourceFileName, string destFileName, bool overwrite) {
            if(!System.IO.File.Exists(sourceFileName))
                throw new FileNotFoundException(sourceFileName+"文件不存在！");
            if(!overwrite&&System.IO.File.Exists(destFileName))
                return false;
            try {
                System.IO.File.Copy(sourceFileName, destFileName, true);
                return true;
            } catch(Exception e) {
                throw e;
            }
        }
        /// <summary>
        /// 备份文件,当目标文件存在时覆盖
        /// </summary>
        /// <param name="sourceFileName">源文件名</param>
        /// <param name="destFileName">目标文件名</param>
        /// <returns>操作是否成功</returns>
        public static bool BackupFile(string sourceFileName, string destFileName) {
            return BackupFile(sourceFileName, destFileName, true);
        }
        /// <summary>
        /// 恢复文件
        /// </summary>
        /// <param name="backupFileName">备份文件名</param>
        /// <param name="targetFileName">要恢复的文件名</param>
        /// <param name="backupTargetFileName">要恢复文件再次备份的名称,如果为null,则不再备份恢复文件</param>
        /// <returns>操作是否成功</returns>
        public static bool RestoreFile(string backupFileName, string targetFileName, string backupTargetFileName) {
            try {
                if(!System.IO.File.Exists(backupFileName))
                    throw new FileNotFoundException(backupFileName+"文件不存在！");
                if(backupTargetFileName!=null) {
                    if(!System.IO.File.Exists(targetFileName))
                        throw new FileNotFoundException(targetFileName+"文件不存在！无法备份此文件！");
                    else
                        System.IO.File.Copy(targetFileName, backupTargetFileName, true);
                }
                System.IO.File.Delete(targetFileName);
                System.IO.File.Copy(backupFileName, targetFileName);
            } catch(Exception e) {
                throw e;
            }
            return true;
        }
        public static bool RestoreFile(string backupFileName, string targetFileName) {
            return RestoreFile(backupFileName, targetFileName, null);
        }
        /// <summary>
        /// 将全角数字转换为数字
        /// </summary>
        /// <param name="SBCCase"></param>
        /// <returns></returns>
        public static string SBCCaseToNumberic(string SBCCase) {
            char[] c = SBCCase.ToCharArray();
            for(int i = 0; i<c.Length; i++) {
                byte[] b = System.Text.Encoding.Unicode.GetBytes(c, i, 1);
                if(b.Length==2) {
                    if(b[1]==255) {
                        b[0]=(byte)(b[0]+32);
                        b[1]=0;
                        c[i]=System.Text.Encoding.Unicode.GetChars(b)[0];
                    }
                }
            }
            return new string(c);
        }
        /// <summary>
        /// 将字符串转换为Color
        /// </summary>
        /// <param name="color"></param>
        /// <returns></returns>
        public static Color ToColor(string color) {
            int red, green, blue = 0;
            char[] rgb;
            color=color.TrimStart('#');
            color=Regex.Replace(color.ToLower(), "[g-zG-Z]", "");
            switch(color.Length) {
                case 3:
                    rgb=color.ToCharArray();
                    red=Convert.ToInt32(rgb[0].ToString()+rgb[0].ToString(), 16);
                    green=Convert.ToInt32(rgb[1].ToString()+rgb[1].ToString(), 16);
                    blue=Convert.ToInt32(rgb[2].ToString()+rgb[2].ToString(), 16);
                    return Color.FromArgb(red, green, blue);
                case 6:
                    rgb=color.ToCharArray();
                    red=Convert.ToInt32(rgb[0].ToString()+rgb[1].ToString(), 16);
                    green=Convert.ToInt32(rgb[2].ToString()+rgb[3].ToString(), 16);
                    blue=Convert.ToInt32(rgb[4].ToString()+rgb[5].ToString(), 16);
                    return Color.FromArgb(red, green, blue);
                default:
                    return Color.FromName(color);
            }
        }
        /// <summary>
        /// 转换长文件名为短文件名
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="repstring"></param>
        /// <param name="leftnum"></param>
        /// <param name="rightnum"></param>
        /// <param name="charnum"></param>
        /// <returns></returns>
        public static string ConvertSimpleFileName(string fullname, string repstring, int leftnum, int rightnum, int charnum) {
            string simplefilename = "", leftstring = "", rightstring = "", filename = "";
            string extname = GetFileExtName(fullname);
            if(extname.StrIsNullOrEmpty())
                return fullname;
            int filelength = 0, dotindex = 0;
            dotindex=fullname.LastIndexOf('.');
            filename=fullname.Substring(0, dotindex);
            filelength=filename.Length;
            if(dotindex>charnum) {
                leftstring=filename.Substring(0, leftnum);
                rightstring=filename.Substring(filelength-rightnum, rightnum);
                if(repstring==""||repstring==null)
                    simplefilename=leftstring+rightstring+"."+extname;
                else
                    simplefilename=leftstring+repstring+rightstring+"."+extname;
            } else
                simplefilename=fullname;
            return simplefilename;
        }
        /// <summary>
        /// 检查颜色值是否为3/6位的合法颜色
        /// </summary>
        /// <param name="color">待检查的颜色</param>
        /// <returns></returns>
        public static bool CheckColorValue(string color) {
            if(color.StrIsNullOrEmpty())
                return false;
            color=color.Trim().Trim('#');
            if(color.Length!=3&&color.Length!=6)
                return false;
            //不包含0-9  a-f以外的字符
            if(!Regex.IsMatch(color, "[^0-9a-f]", RegexOptions.IgnoreCase))
                return true;
            return false;
        }
        /// <summary>
        /// 合并字符
        /// </summary>
        /// <param name="source">要合并的源字符串</param>
        /// <param name="target">要被合并到的目的字符串</param>
        /// <param name="mergechar">合并符</param>
        /// <returns>合并到的目的字符串</returns>
        public static string MergeString(string source, string target) {
            return MergeString(source, target, ",");
        }
        /// <summary>
        /// 合并字符
        /// </summary>
        /// <param name="source">要合并的源字符串</param>
        /// <param name="target">要被合并到的目的字符串</param>
        /// <param name="mergechar">合并符</param>
        /// <returns>并到字符串</returns>
        public static string MergeString(string source, string target, string mergechar) {
            if(target.StrIsNullOrEmpty())
                target=source;
            else
                target+=mergechar+source;
            return target;
        }
        /// <summary>
        /// 清除UBB标签
        /// </summary>
        /// <param name="sDetail">帖子内容</param>
        /// <returns>帖子内容</returns>
        public static string ClearUBB(string sDetail) {
            return Regex.Replace(sDetail, @"\[[^\]]*?\]", string.Empty, RegexOptions.IgnoreCase);
        }
        /// <summary>
        /// 使用正则表达式删除代码中的所有空行
        /// </summary>
        public static string ClearBlankLine(string text) {
            return Regex.Replace(text, @"^\s*$[\r\n]*", string.Empty, RegexOptions.IgnoreCase);
        }
        /// <summary>
        /// 获取指定文件的扩展名
        /// </summary>
        /// <param name="fileName">指定文件名</param>
        /// <returns>扩展名</returns>
        public static string GetFileExtName(string fileName) {
            if(fileName.StrIsNullOrEmpty()||fileName.IndexOf('.')<=0)
                return "";
            fileName=fileName.ToLower().Trim();
            return fileName.Substring(fileName.LastIndexOf('.'), fileName.Length-fileName.LastIndexOf('.'));
        }
        public static string GetHttpWebResponse(string url) {
            return GetHttpWebResponse(url, string.Empty);
        }
        /// <summary>
        /// http POST请求url
        /// </summary>
        /// <returns></returns>
        public static string GetHttpWebResponse(string url, string postData) {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method="POST";
            request.ContentType="application/x-www-form-urlencoded";
            request.ContentLength=postData.Length;
            request.Timeout=20000;
            HttpWebResponse response = null;
            try {
                StreamWriter swRequestWriter = new StreamWriter(request.GetRequestStream());
                swRequestWriter.Write(postData);
                if(swRequestWriter!=null)
                    swRequestWriter.Close();
                response=(HttpWebResponse)request.GetResponse();
                using(StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) {
                    return reader.ReadToEnd();
                }
            } finally {
                if(response!=null)
                    response.Close();
            }
        }
        /// <summary>
        /// 将8位日期型整型数据转换为日期字符串数据
        /// </summary>
        /// <param name="date">整型日期</param>
        /// <param name="chnType">是否以中文年月日输出</param>
        /// <returns></returns>
        public static string FormatDate(int date, bool chnType) {
            string dateStr = date.ToString();
            if(date<=0||dateStr.Length!=8)
                return dateStr;
            if(chnType)
                return dateStr.Substring(0, 4)+"年"+dateStr.Substring(4, 2)+"月"+dateStr.Substring(6)+"日";
            return dateStr.Substring(0, 4)+"-"+dateStr.Substring(4, 2)+"-"+dateStr.Substring(6);
        }
        public static string FormatDate(int date) {
            return FormatDate(date, false);
        }
        public static T GetObjTranNull<T>(object obj) {
            try {
                if(obj==null) {
                    return (T)System.Convert.ChangeType("", typeof(T));
                } else {
                    if(obj.GetType()==typeof(T))
                        return (T)obj;
                }
                return (T)System.Convert.ChangeType(obj, typeof(T));
            } catch { }
            return default(T);
        }
    }
}
